<script lang="ts" setup>
import router from '@/router';
import type { GetParkEnterpriseParams, GetParkRentBuildingData, PostParkEnterpriseRentParams, Row, Enterprise, Rent, EnterpriseWithRent } from '@/types/enterprise';
import { PostUploadAPI } from '@/utils/commen';
import { DeleteParkEnterprise, DeleteParkEnterpriseRentAPI, GetParkEnterpriseParamsAPI, GetParkEnterpriseRentAPI, GetParkRentBuildingAPI, PostParkEnterpriseRentAPI, PutParkEnterpriseRentAPI } from '@/utils/enterprise';
import { ElMessage,ElMessageBox,type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { ro } from 'element-plus/es/locales.mjs';
import { ref, watch } from 'vue';



const params = ref<GetParkEnterpriseParams>({
  name:'',
  page:1,
  pageSize:10
})
const total = ref(0)
const EnterpriseList = ref<EnterpriseWithRent[]>([])
// 获取企业列表
const Getenterprise = async() =>{
  const res = await GetParkEnterpriseParamsAPI(params.value)
 // map映射数组用于前端展示

  EnterpriseList.value = res.data?.rows.map((item)=>({
    ...item,
    rentList:[] //合同列表默认值，用于嵌套表格渲染
  }))
  total.value = res.data?.total
}

Getenterprise()

// 表格展开时触发的事件
//  获取企业租赁信息
const getRentList = async (row:EnterpriseWithRent) =>{
  // 根据id获取合同列表
   const res = await GetParkEnterpriseRentAPI(row.id)
  // 把合同列表添加到企业信息中
  row.rentList = res.data
  
}
// 搜素业务
const onSearch = ()=>{
  // 重置页码
  params.value.page = 1
  // 获取数据
  Getenterprise()

}

// 删除企业

const DelEnterprise = async(id:string) =>{
  try{
    const res = await  DeleteParkEnterprise(id)
    console.log(res);
    ElMessage.success('删除成功')
    Getenterprise ()
  } catch(error){
  }
}



// 可租赁楼宇
const avaiavleRentBuilding = ref<GetParkRentBuildingData[]>()


const rentDialogVisible = ref(false)
// 打开弹窗
const addRent = async(id:number) =>{
  // 打开弹窗
  rentDialogVisible.value = true
  //  打开弹窗时获取可租赁楼宇列表
  const res = await GetParkRentBuildingAPI()
  avaiavleRentBuilding.value =  res.data
  console.log('可租赁楼宇',res);
  
  // 保存企业id 用于添加合同
  RentForm.value.enterpriseId = id
}

const fileList  = ref<UploadUserFile[]>([])
// 关闭
const closeDialog = () =>{
  rentDialogVisible.value = false
  // 清除表单信息
  addFormRef.value?.resetFields()
  // 清除表单信息只能够清除选择列表，日期和需要单独清除
  timeArr.value = []
  // // 清除
  fileList.value = []
  RentForm.value = initRentForm()
  
  
}


// 表单默认数据，每次调用返回一个新对象
const initRentForm = () =>{
 return {
      /**r
   * 租赁楼宇id
   */
   buildingId: undefined,
  /**
   * 合同附件id
   */
  contractId: 0,
  /**
   * 合同附件url
   */
  contractUrl: '',
  /**
   * 租赁结束日期
   */
  endTime: '',
  /**
   * 企业id
   */
  enterpriseId: 0,
  /**
   * 开始日期（不能小于今日日期）
   */
  startTime: '',
  /**
   * 操作类型，添加合同0，续签合同1
   */
  type: 0,
 }
}
// 租赁楼宇表单

const RentForm = ref<PostParkEnterpriseRentParams>(initRentForm())


// 租赁合同规则
const buildingFormRules = ref<FormRules<PostParkEnterpriseRentParams>>({
  buildingId:[
    { required:true, message:'请选择租赁楼宇',trigger:'change'}
  ],
  endTime:[
    { required:true,message:'请选择租赁起止时间',trigger:'blur'}
  ],
  contractId:[
    { required:true,message:'请上传合同文件',trigger:'blur'}
  ],
contractUrl:[
{ required:true,message:'请上传合同文件',trigger:'blur'}
]
})
// 时间选择器 监听时间变化
const timeArr = ref<string[]>([])

watch(timeArr,(val)=>{
  if(val){
    console.log(val);
    RentForm.value.startTime = val[0]
    RentForm.value.endTime = val[1]
  }else{
    RentForm.value.startTime = ''
    RentForm.value.endTime = ''
  }
},{
  deep:true
})

//   // 通过 disabledDate 函数，来设置禁用掉的日期。
const disabledDate = (time:Date)=>{

  // 不能小于今日日期 包含今天 (1000 *60 *60 *24 >1天的毫秒数)
  return time.getTime() < Date.now() -1000 * 60 * 60 *24
}
// 获取表单
const addFormRef = ref<FormInstance>()

// 上传合同文件
const onUploadRequest = async(options: UploadRequestOptions) =>{
  // 1.准备Form对象
  const fd = new FormData()
  fd.append('file',options.file)
  fd.append('type','contract')
  // 2.发送请求，上传文件
  const res = await PostUploadAPI(fd)
  console.log('上传合同文件',res);
  
  // 3.保存合同附件 url 和 id ，用于添加合同
  RentForm.value.contractUrl = res.data.url
  RentForm.value.contractId = res.data.id
  // 4.主动触达校验 通过就会清楚错误信息
  addFormRef.value?.validateField('contractUrl')
  // 5.return 后端返回的数据 保存到response中
  return res.data 
}
// 删除合同文件
const removeUpload = () =>{
  // 清空数据
  RentForm.value.buildingId = undefined
  RentForm.value.contractUrl = ''
  // 触发校验
  addFormRef.value?.validateField('contractUrl')
}

// 上传文件前触发事件
const beforeUpload = (rawFile: UploadRawFile) =>{
  // size尺寸是Byte , 5M =5 *1024 *1024
  const allowSize = 5 *1024 *1024
  // 检测文件大小
  if(rawFile.size > allowSize){
    ElMessage.error('文件过大，请重新上传5M以下的文件')
    return false
  }
  return true
}


// 删除合同
const deleteRent = (rentRow:Rent,enterPriseRow:EnterpriseWithRent) =>{
  ElMessageBox.confirm('删除不可撤回，是否确认删除当前合同?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 发送请求，删除后端合同
    await DeleteParkEnterpriseRentAPI(rentRow.id)
    // 删除过滤掉合同
    enterPriseRow.rentList = enterPriseRow.rentList.filter((item)=>item.id !== rentRow.id)
    // 轻提示
    ElMessage.success('删除成功')
   // .重新获取企业列表
   getRentList(EnterpriseList.value[0])
  }).catch(() => {
    // 点击取消，什么也不做
  })
}

// 上传合同
const addRentConfim = async () =>{
  try{
    // 1.表单校验
    await addFormRef.value?.validate()
      // 2.发送请求
      await PostParkEnterpriseRentAPI(RentForm.value)
      // 3.提示
      ElMessage.success('添加成功')
      // 4.关闭弹窗
      closeDialog()
      // 5.重新获取企业列表
      getRentList(EnterpriseList.value[0])
  }catch(error){

  }
  
}

// 表格数据
const enterpriseList = ref<EnterpriseWithRent[]>([])
// 退租业务
// 退租合同
const outRent = (row:Rent) => {
    ElMessageBox.confirm('退租不可撤回，是否确认退租当前楼宇?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      // 发送请求，更新后端合同状态
      await PutParkEnterpriseRentAPI(row.id)
      // 轻提示
      ElMessage.success('退租成功')
      // 重新获取企业列表
      getRentList(EnterpriseList.value[0])
     
    }).catch(() => {
      // 点击取消，什么也不做
    })
  }


</script>
<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input clearable placeholder="请输入内容" @clear="onSearch()" class="search-main" v-model="params.name"  />
      <el-button type="primary" @click="onSearch()">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/addenterprise')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="EnterpriseList" @expand-change="getRentList" row-key="id">
        <!-- @expand-change 展开或折叠行时触发 -->

            <el-table-column type="expand">
              <template v-slot="{row}">
                <el-table :data="row.rentList">
                  <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
                  <el-table-column label="租赁起始时间"  prop="startTime" />
                  <el-table-column label="合同状态" prop="status" >
                  <template v-slot="{row}">
                    <el-tag  v-if="row.status === 0" type="warning">待生效</el-tag>
                    <el-tag  v-if="row.status === 1" type="success">生效中</el-tag>
                    <el-tag  v-if="row.status === 2" type="info">已到期</el-tag>
                    <el-tag  v-if="row.status === 3" type="danger">已退租</el-tag>
                  </template>
                  </el-table-column>
                  <el-table-column label="操作" width="220">
                    <template #default="{row:rentRow}">
                      <el-button size="small" type="text" :disabled="row.status === 3">续租</el-button>
                      <el-button size="small" type="text" :disabled="row.status ! === 3" @click="outRent(row)">退租</el-button>
                      <el-button size="small" type="text" @click="deleteRent(rentRow,row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人"  width="120" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber"/>
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button size="small" type="text" @click="addRent(row.id)">添加合同</el-button>
            <el-button size="small" type="text" @click="$router.push(`/enterprisedetail/${row.id}`)">查看</el-button>
            <el-button size="small" type="text" @click="router.push(`/addenterprise/${row.id}`)">编辑</el-button>
            <el-button size="small" type="text" @click="DelEnterprise(`${row.id}`)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination :total="total" layout="total,sizes, prev, pager, next,jumper"
      :page-sizes="[2,5,10]"
      v-model:page-size="params.pageSize"
      v-model:current-page="params.page" 
      @change="Getenterprise"
      />  
    </div>
        <el-dialog title="添加合同" v-model="rentDialogVisible" width="580px" @close="closeDialog">
              <!-- 表单模版 -->
              {{ RentForm }}
            <div class="form-container">
              <el-form ref="addFormRef" :model="RentForm" :rules="buildingFormRules" label-position="top">
                <el-form-item label="租赁楼宇" prop="buildingId">
                  <el-select v-model="RentForm.buildingId" placeholder="请选择">
                    <el-option v-for="item in avaiavleRentBuilding" :key="item?.id" :label="item?.name" :value="item.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="租赁起止日期" prop="endTime">
                  <el-date-picker v-model="timeArr" type="daterange" range-separator="至" start-placeholder="开始日期"
                    end-placeholder="结束日期" value-format="YYYY-MM-DD" :disabled-date="disabledDate" />
                </el-form-item>
                <el-form-item label="租赁合同" prop="contractUrl">
                  <el-upload accept=".doc, .pdf"
                  :http-request="onUploadRequest"
                  @remove="removeUpload"
                  :before-upload="beforeUpload"
                  :file-list="fileList"	
                  >
                    <el-button size="small" type="primary" plain>上传合同文件</el-button>
                    <template #tip>
                      <div class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
                    </template>
                  </el-upload>
                </el-form-item>
              </el-form>
            </div>
           
              <template #footer>
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="addRentConfim">确 定</el-button>
              </template>
            </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>